package com.momoauth.common.tps.aliyun.service;

import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponseBody;
import com.momoauth.common.tps.aliyun.utils.AliyunSmsUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.concurrent.ExecutionException;

@Slf4j
public class AliyunSmsService {

    /**
     * 请填写你从阿里云获取的AK信息
     * 获取地址：https://usercenter.console.aliyun.com/#/manage/ak
     */

    private final String accessKeyID;
    private final String accessKeySecret;

    public AliyunSmsService(String accessKeyID, String accessKeySecret) {
        this.accessKeyID = accessKeyID;
        this.accessKeySecret = accessKeySecret;
    }

    /**
     * 发送短信
     * @param phoneNumbers 接收短信的手机号码
     * @param templateMap 短信模板内容
     * @throws ExecutionException
     * @throws InterruptedException
     */
    public boolean sendSMS(String phoneNumbers, Map<String, String> templateMap) throws ExecutionException, InterruptedException {
        SendSmsResponseBody responseBody = null;
        if (!ObjectUtils.isEmpty(phoneNumbers) && !templateMap.isEmpty()) {
            // 短信签名名称
            String signName = templateMap.get("signName");
            // 短信模板CODE
            String templateCode = templateMap.get("templateCode");
            // 短信模板变量对应的实际值
            String templateParam = templateMap.get("templateParam");
            // 请求发送
            responseBody = AliyunSmsUtil.sendSMS(
                    accessKeyID,
                    accessKeySecret,
                    phoneNumbers,
                    signName,
                    templateCode,
                    templateParam
            );
            // 根据返回的CODE值判断是否发送成功
            if (responseBody.getCode().equals("OK")) {
                log.info("SMS OK");
                return true;
            }
        }
        assert responseBody != null;
        log.error(responseBody.getMessage());
        return false;
    }
}
